/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClientGUI.java
 *
 * Created on 26/Out/2009, 21:17:02
 */

package tp_sd_cliente.gui;

import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractListModel;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import tp_sd_base.IServer;
import tp_sd_base.IServer.ERROR_TYPE;
import tp_sd_base.Set;
import tp_sd_cliente.model.ClientChat;


/**
 *
 * @author kill9
 */
public class ClientGUI extends javax.swing.JFrame implements ClientChat.IClientListener{

    private static ClientGUI cgui = new ClientGUI();

    public static ClientGUI getInstance(){
        return cgui;
    }

    private ClientChat clientChat;

    private LogInGUI logInGUI;

    private static String login;

    private List<String> online = new ArrayList<String>();

    private List<String> followers = new ArrayList<String>();

    private List<String> followed = new ArrayList<String>();

    private JPopupMenu menu;

    /** Creates new form ClientGUI */
    private ClientGUI() {
        
            initComponents();
            logInGUI = new LogInGUI(this);
            textboard.setEditable(false);
    }

    public void setClientChat(ClientChat clientChat) {
        this.clientChat = clientChat;
        logInGUI.setClientChat(clientChat);
    }
    

    public void setUsers(List<String> list){
        users.setModel(new UserListModel(list));
    }

    public void addUser(String user){
        ((UserListModel)users.getModel()).addUser(user);
    }

    public void removeUser(String user){
        ((UserListModel)users.getModel()).removeUser(user);
    }

    public void addMessage(String user ,String msg){
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        builder.append(user);
        builder.append("]  ");
        builder.append(msg);
        builder.append("\n");

        this.textboard.append(builder.toString());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textboard = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        users = new javax.swing.JList();
        text = new javax.swing.JTextField();
        send = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jToolBar1 = new javax.swing.JToolBar();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cliente Chat");
        setResizable(false);

        jPanel1.setBackground(java.awt.Color.white);

        textboard.setColumns(20);
        textboard.setRows(5);
        textboard.setWrapStyleWord(true);
        jScrollPane1.setViewportView(textboard);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jPanel2.setBackground(java.awt.Color.white);

        users.setModel(new UserListModel());
        users.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                usersMouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(users);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
        );

        text.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                textKeyReleased(evt);
            }
        });

        send.setText("Enviar");
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Online", "Seguidores", "Seguidos" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jButton1.setText("+");
        jButton1.setToolTipText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("-");
        jButton2.setToolTipText("Remove");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2))
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.TRAILING, 0, 152, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addComponent(text, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(send, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(3, 3, 3))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(send))
                .addGap(40, 40, 40))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(281, Short.MAX_VALUE))
        );

        jPanel3.setBounds(0, 0, 520, 320);
        jLayeredPane1.add(jPanel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jToolBar1.setFloatable(false);

        jMenu1.setText("File");

        jMenuItem2.setText("Exit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Option");

        jMenuItem1.setText("Refresh");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuItem3.setText("Top 10 Messaging");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem3);

        jMenuItem4.setText("Top 10 Followers");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem4);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLayeredPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 530, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-536)/2, (screenSize.height-398)/2, 536, 398);
    }// </editor-fold>//GEN-END:initComponents



    private void sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendActionPerformed
        sendMessage(text.getText());
        text.setText("");
    }//GEN-LAST:event_sendActionPerformed

   public void onException(Exception exc) {
        JOptionPane.showMessageDialog(this, exc.toString(), "Excepção", JOptionPane.ERROR_MESSAGE);

    }


    private void sendMessage(String message){
        try {
            String string = message.trim();
            if(string.length()>0){
                addMessage("-->>", message);
            this.clientChat.sendMessage(message);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void textKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textKeyReleased
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
            sendMessage(text.getText());
            text.setText("");
        }
    }//GEN-LAST:event_textKeyReleased

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        String string = evt.getItem().toString();
                if(string.equals("Seguidores")){
                setUsers(followers);
            }else{
                if(string.equals("Seguidos")){
                    setUsers(followed);
                }else{
                    setUsers(online);
                }
            }
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void usersMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_usersMouseReleased
        
    }//GEN-LAST:event_usersMouseReleased

   private List<String> getSelection(){
    List<String> list = new ArrayList<String>();
    for(Object object : users.getSelectedValues()){
        list.add(object.toString());
    }

    return list;
   }


    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        List<String> list = getSelection();
        if(list.size()>0){
            try {
                clientChat.sendAddUsers(list);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(),"Erro",JOptionPane.ERROR);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        List<String> list = getSelection();
        if(list.size()>0){
            try {
                clientChat.sendRemoveUsers(list);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(),"Erro",JOptionPane.ERROR);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        try {
            clientChat.refresh();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR);
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        try {
            clientChat.disconnect();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR);
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        try{
            clientChat.topUserMessages();
        }catch(IOException  ioe){
            ioe.printStackTrace();
        }
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        try {
            clientChat.topUserFollowers();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    
    
    private class  UserListModel<K> extends AbstractListModel{

        private List<K> list;

        public UserListModel() {
            list = new ArrayList<K>();
        }

        public UserListModel(List<K> list) {
            Iterator<K> iterator = list.iterator();
            while(iterator.hasNext()){
                if(iterator.next().equals(ClientGUI.login)){
                    iterator.remove();
                }
            }
            this.list = list;
        }

        public int getSize() {
            return list.size();
        }

        public Object getElementAt(int index) {
            return  list.get(index);
        }

        public void addUser(K user){
            if(!list.contains(user)){
                this.list.add(user);
                this.fireIntervalAdded(user,list.size()-1, list.size()-1);
            }
        }

        public void removeUser(K user){
            if(this.list.remove(user)){
                this.fireIntervalRemoved(user,list.size(), list.size());
            }
        }
        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton send;
    private javax.swing.JTextField text;
    private javax.swing.JTextArea textboard;
    private javax.swing.JList users;
    // End of variables declaration//GEN-END:variables



        public void onError(ERROR_TYPE eRROR_TYPE, String errorType){
            switch(eRROR_TYPE){
                case LOGIN : onLogOut();break;
                case REGISTRATION : onLogOut();break;
            }
            JOptionPane.showMessageDialog(this, errorType, "Erro", JOptionPane.ERROR_MESSAGE);

        }

        public void onLogin(String readUTF){
            logInGUI.onLogIn();
            this.login = readUTF;
            this.setTitle(readUTF);
        }

        public void onLogOut(){
        try {
            if(clientChat!=null && !clientChat.isClosed())
                clientChat.disconnect();
            ClientChat clientChat = new ClientChat();
            clientChat.setListener(this);
            this.setClientChat(clientChat);
            logInGUI.onLogOut();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        }

        public void onMessage(String nickName, String readUTF){
            this.addMessage(nickName, readUTF);
        }

        public void onRanking(int readInt, List<Set<String,Integer>> list){
            String string = list.toString().replace(",", "\n").replace("[", "").replace("]", "");
            JOptionPane.showMessageDialog(this, string,"Top 10 "+(readInt==IServer.RANKING.MESSAGES.ordinal()?"Messaging":"Followers"),JOptionPane.INFORMATION_MESSAGE);
        }

        public void onRefresh(int readInt, List<String> list){
            switch(IServer.REFRESH_TYPE.values()[readInt]){
                case FOLLOWED: followed = list;break;
                case FOLLOWERS :followers = list;break;
                case ONLINE : online = list;break;
            }
            refreshList();
        }

        public void onInvalidOperation(int value){

            
        }

        public void onInvalidArgs(){
            onLogOut();
        }

    public void onPartialRefresh(int readInt, int operation,List<String> list) {
            switch(IServer.REFRESH_TYPE.values()[readInt]){
                case FOLLOWED: if(operation == IServer.OPERATION.ADD.ordinal())
                                    addAll(followed, list);
                                else
                                    followed.removeAll(list);
                    break;
                case FOLLOWERS : if(operation == IServer.OPERATION.ADD.ordinal())
                                    addAll(followers, list);
                                else
                                    followers.removeAll(list);
                    break;
                case ONLINE : if(operation == IServer.OPERATION.ADD.ordinal())
                                    addAll(online, list);
                                else
                                    online.removeAll(list);
                    break;
            }
            refreshList();
    }

    private static <K> void addAll(List<K> l, List<K> l1){
        for(K k : l1){
            if(!l.contains(k)){
                l.add(k);
            }
        }
    }

    private void refreshList(){
        String string = jComboBox1.getSelectedItem().toString();
                if(string.equals("Seguidores")){
                    setUsers(followers);
            }else{
                if(string.equals("Seguidos")){
                    setUsers(followed);
                }else{
                    setUsers(online);
                }
            }
    }

}
